import java.util.Arrays;

/**
 * 不允许null元素
 * 2018年 03月 20日 星期二
 *
 * @author fireway
 */
public class ObjectArray<E> {
    /**
     * The array buffer into which the elements of the ObjectArray are stored.
     * The capacity of the ObjectArray is the length of this array buffer.
     */
    private Object[] mDatas;

    /**
     * The size of the ObjectArray (the number of elements it contains).
     */
    private int mSize;

    public ObjectArray() {
        this(10);
    }

    public ObjectArray(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
        }

        mDatas = new Object[initialCapacity];
        mSize = 0;
    }

    public void insert(E e) {
        if (mSize == mDatas.length) {
            System.out.println("Can not insert " + e);
            return;
        }
        mDatas[mSize++] = e;
    }

    public boolean delete(Object o) {
        int i = indexOf(o);
        if (-1 == i) {
            return false;
        } else {
            // 注意这里应该是j小于mSize -1
            // for (int j = i; j < mSize - 1; j++) {
            //     mDatas[j] = mDatas[j + 1];
            // }
            System.arraycopy(mDatas, i + 1, mDatas, i, mSize - i - 1);
            mSize--;
            return true;
        }
    }

    /**
     * Returns the index of the first occurrence of the specified element
     * in this array, or -1 if this array does not contain the element.
     */
    public int indexOf(Object o) {
        if (null == o) {
            for (int i = 0; i < mSize; i++) {
                if (o == mDatas[i]) {
                    return i;
                }
            }
        } else {
            for (int i = 0; i < mSize; i++) {
                if (o.equals(mDatas[i])) {
                    return i;
                }
            }
        }
        return -1;
    }

    public int size() {
        return mSize;
    }

    /**
     * 插入排序
     */
    @SuppressWarnings("unchecked")
    public void insertSort() {
        for (int i = 1; i < mSize; i++) {
            String order = String.format("%2s", i);
            System.out.print("order" + order + " : ");

            Object tmp = mDatas[i];
            int j = i;

            while ( j > 0 && (((Comparable)mDatas[j - 1])).compareTo((Comparable)tmp) > 0 ) {
                mDatas[j] = mDatas[j - 1];
                j--;
            }

            mDatas[j] = tmp;

            System.out.print(Arrays.toString(mDatas));
            System.out.println("");
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (int i = 0; i < mSize; i++) {
            sb.append(mDatas[i]);
            if (i == mSize -1) {
                break;
            }
            sb.append(", ");
        }
        sb.append(']');
        return sb.toString();
    }
}

